﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace MDCAdminTool.Controls
{
    public partial class AsyncProgressBar : UserControl
    {
        private readonly DispatcherTimer timer;
        
        #region StartProgress Event
        public static readonly RoutedEvent StartProgressEvent = 
            EventManager.RegisterRoutedEvent(
                            "StartProgress" ,
                            RoutingStrategy.Bubble ,
                            typeof( RoutedEventHandler ) ,
                            typeof( AsyncProgressBar ) );


        public event RoutedEventHandler StartProgress
        {
            add { AddHandler( StartProgressEvent , value ); }
            remove { RemoveHandler( StartProgressEvent , value ); }
        } 
        #endregion

        #region StopProgress Event
        public static readonly RoutedEvent StopProgressEvent = 
            EventManager.RegisterRoutedEvent(
                            "StopProgress" ,
                            RoutingStrategy.Bubble ,
                            typeof( RoutedEventHandler ) ,
                            typeof( AsyncProgressBar ) );

        public event RoutedEventHandler StopProgress
        {
            add { AddHandler( StopProgressEvent , value ); }
            remove { RemoveHandler( StopProgressEvent , value ); }
        }
        #endregion

        public AsyncProgressBar()
        {
            timer          = new DispatcherTimer {Interval = new TimeSpan(0, 0, 0, 1)};
            timer.Tick     += TimerTick;

            InitializeComponent();
        }

        void TimerTick( object sender , EventArgs e )
        {
            if ( progressBar1.Value >= 100 )
                progressBar1.Value = 0;

            progressBar1.Value += 10;
        }

        public void Start()
        {
            timer.Start();
            progressBar1.Dispatcher.Invoke(
                new Action(
                    () => RaiseEvent( new RoutedEventArgs( StartProgressEvent , this ) )) );
           
        }
        public void Stop()
        {
            timer.Stop();

            progressBar1.Dispatcher.Invoke(
                new Action(
                    () =>
                        {
                            progressBar1.Value = 0;
                            RaiseEvent( new RoutedEventArgs( StopProgressEvent , this ) );
                        }));
        }
    }
}
